var page = {
  pageNum: 1,
  pageSize: 10,
};
$(function () {
  leftTree();
  renderForm();

  layui.use("tree", function () {
    // var tree = layui.tree;
    // $(".selectSpan").on("click", function () {
    //   $("#selectData").fadeIn();
    //   $.ajax({
    //     method: "post",
    //     url: "/youtian/scene-category/since-dept-tree",
    //     success: function (res) {
    //       var tree = layui.tree;
    //       var inst1 = tree.render({
    //         elem: "#selectData",
    //         data: res.data,
    //         click: function (obj) {
    //           console.log(obj, "obj");
    //           $("#selectData").fadeOut();
    //           if (obj.data.labelType == "dept") {
    //             onparentId = "";
    //             $(".selectSpan").val();
    //             layui.layer.msg("请重新选择工作区级别", { icon: 5 });
    //           } else {
    //             onparentId = obj.data.id;
    //             $(".selectSpan").html(obj.data.title);
    //           }
    //         },
    //       });
    //     },
    //   });
    // });
  });

  // 点击新增
  var selectClickVal;
  function selectClick() {
    $(".selectClick").children().remove();
    $(".selectClick").append($("<option/>").text("请选择").attr("value", ""));
    let data = {
      deptId: null,
      ejdw_id: $("#selset-formTwo").val(),
      dw_3_id: $("#selset-formThree").val(),
      dw_4_id: $("#selset-formFour").val(),
      dw_5_id: $("#selset-formFive").val(),
    };
    console.log(data, "data");
    $.ajax({
      method: "POST",
      url: "/gzmx_tag/gzmx_tag/list",
      data: data,
      success: function (res) {
        console.log(res, "datares");
        selectClickVal = res.rows;
        for (let i = 0; i < res.rows.length; i++) {
          // text+=`<option value=${tabelDatas[i].pointId}>${tableDatas[i].pointName}</option>`
          $(".selectClick").append(
            $("<option/>")
              .text(res.rows[i].description)
              .attr("value", res.rows[i].sourceTag)
          );
        }
      },
    });
  }
  $(".selectClick").change(function () {
    let val = $(".selectClick").val();
    console.log(val, "val");
    let selectClickdata = selectClickVal.filter((item) => {
      return item.sourceTag == val;
    });
    console.log(selectClickdata);
    $("#upperLimit").val(selectClickdata[0].max_value);
    $("#lowerLimit").val(selectClickdata[0].min_value);
  });

  /**
   * 接口为3.4.1
   */
  function scdwList() {
    $.ajax({
      method: "post",
      url: "/gzmx_scdw/gzmx_scdw/list",
      data: { jb: 1 },
      success: function (res) {
        console.log("绑定点位下拉框", res);
        for (let i = 0; i < res.length; i++) {
          // text+=`<option value=${tabelDatas[i].pointId}>${tableDatas[i].pointName}</option>`
          $("#selset-formOne").append(
            $("<option/>").text(res[i].dwmc).attr("value", res[i].id)
          );
        }
      },
    });
  }
  $("#selset-formOne").change(function () {
    $("#selset-formTwo").children().remove();
    $("#selset-formTwo").append(
      $("<option/>").text("请选择").attr("value", "")
    );
    console.log(111);
    let ejdwId = $("#selset-formOne").val();
    $.ajax({
      method: "post",
      url: "/gzmx_scdw/gzmx_scdw/list",
      data: { fdwdm: ejdwId },
      success: function (res) {
        console.log("绑定点位", res);
        for (let i = 0; i < res.length; i++) {
          // text+=`<option value=${tabelDatas[i].pointId}>${tableDatas[i].pointName}</option>`
          $("#selset-formTwo").append(
            $("<option/>").text(res[i].dwmc).attr("value", res[i].id)
          );
        }
      },
    });
    selectClick();
  });
  $("#selset-formTwo").change(function () {
    console.log(111);
    $("#selset-formThree").children().remove();
    $("#selset-formThree").append(
      $("<option/>").text("请选择").attr("value", "")
    );
    let dw_3_id = $("#selset-formTwo").val();
    $.ajax({
      method: "post",
      url: "/gzmx_scdw/gzmx_scdw/list",
      data: { fdwdm: dw_3_id },
      success: function (res) {
        console.log("绑定点位", res);
        for (let i = 0; i < res.length; i++) {
          // text+=`<option value=${tabelDatas[i].pointId}>${tableDatas[i].pointName}</option>`
          $("#selset-formThree").append(
            $("<option/>").text(res[i].dwmc).attr("value", res[i].id)
          );
        }
      },
    });
    selectClick();
  });
  $("#selset-formThree").change(function () {
    console.log(111);
    let dw_4_id = $("#selset-formThree").val();
    $("#selset-formFour").children().remove();
    $("#selset-formFour").append(
      $("<option/>").text("请选择").attr("value", "")
    );
    // console.log($('#selset-formFour').children());
    $.ajax({
      method: "post",
      url: "/gzmx_scdw/gzmx_scdw/list",
      data: { fdwdm: dw_4_id },
      success: function (res) {
        console.log("绑定点位", res);
        for (let i = 0; i < res.length; i++) {
          // text+=`<option value=${tabelDatas[i].pointId}>${tableDatas[i].pointName}</option>`
          $("#selset-formFour").append(
            $("<option/>").text(res[i].dwmc).attr("value", res[i].id)
          );
        }
      },
    });
    selectClick();
  });
  $("#selset-formFour").change(function () {
    $("#selset-formFive").children().remove();
    $("#selset-formFive").append(
      $("<option/>").text("请选择").attr("value", "")
    );
    console.log(111);
    let dw_5_id = $("#selset-formFour").val();
    $.ajax({
      method: "post",
      url: "/gzmx_scdw/gzmx_scdw/list",
      data: { fdwdm: dw_5_id },
      success: function (res) {
        console.log("绑定点位", res);
        for (let i = 0; i < res.length; i++) {
          // text+=`<option value=${tabelDatas[i].pointId}>${tableDatas[i].pointName}</option>`
          $("#selset-formFive").append(
            $("<option/>").text(res[i].dwmc).attr("value", res[i].id)
          );
        }
      },
    });
    selectClick();
  });

  // 点击出现监测点录入框弹窗
  var luruindex;
  $("#addBTN").click(function (e) {
    e.preventDefault();
    luruindex = layer.open({
      type: 1,
      title: ["新增监测点", "font-size:18px;"],
      area: ["70%", "70%"],
      content: $("#newAreaShow"),
      move: false,
      cancel: function () {
        $("#upperLimit").val("");
        $("#lowerLimit").val("");
      },
    });
    scdwList();

    $(".workspace").val(treeData.title);
  });

  // 点击保存按钮新增监测点
  $("#jiancedianPop").click(function (e) {
    let data = {
      sceneId: detail.data.sceneId,
      pointId: $("#selset-form").val(),
    };
    console.log(data, " dataa");
    console.log(data, "sssdata");
    e.preventDefault();
    $.ajax({
      method: "post",
      url: "/youtian/scene-point",
      data: JSON.stringify(data),
      dataType: "json",
      contentType: "application/json",
      success: function (res) {
        // let sceneId = detail.data.sceneId;
        // $.ajax({
        //   url: `/youtian/scene-category/scencePointlist`,
        //   method: "post",
        //   data: JSON.stringify({ sceneId: sceneId }),
        //   contentType: "application/json",
        //   success: function (res) {
        //     // layer.close(loading); // 关闭加载中
        //     layui.layer.close(luruindex);
        //     tableList(res);
        //   },
        // });
        page.sceneId = detail.data.sceneId;
        $.ajax({
          url: `/youtian/scene-category/scencePointlist`,
          type: "get",
          data: page,
          success: function (res) {
            tableList(res);
          },
        });
        layui.layer.close(luruindex);
        console.log(res, " ------------res");
      },
    });
  });

  // 初次进入渲染表格数据
  /**
   * 接口为序号3.4
   */
  function firstTable() {
    $.ajax({
      url: `/youtian/scene-category/list`,
      type: "get",
      data: {
        pageNum: 1,
        pageSize: 10000,
      },
      success: function (res) {
        console.log(res, "tableRes");
        tablePop(res);
      },
    });
  }
  firstTable();

  var clickTreeId = "";
  var treeData = {};
  // 渲染form表单
  function renderForm(id, pointId, index, flag) {
    layui.use("form", function () {
      var form = layui.form;
      // 防止渲染多遍
      // if(flag){
      $.ajax({
        url: `/youtian/equipment/list`,
        type: "post",
        dataType: "json",
        headers: { "Content-Type": "application/json" },
        data: JSON.stringify({
          sceneId: clickTreeId,
        }),
        success: function (res) {
          var optionText = "<option>请选择</option>";
          for (let i = 0; i < res.data.length; i++) {
            optionText += `<option class=options value=${res.data[i].equipmentId}>${res.data[i].equipmentName}</option>`;
          }
          $("#layform .selectData").append(optionText);
          form.render();
        },
      });
      // }

      var selectData = "";
      form.on("select", function (data) {
        selectData = data.value;
      });
      //提交事件

      $("#layform").on("submit", function (e) {
        e.preventDefault();
        // for(let i =0;i<selectOptions.length;i++) {
        if (selectData) {
          $.ajax({
            url: "/youtian/point-equipment",
            type: "post",
            dataType: "json",
            headers: { "Content-Type": "application/json" },
            data: JSON.stringify({
              pointId: tableItem.pointId,
              equipmentId: selectData,
            }),
            success: function (res) {
              if (res.code !== 0) {
                layui.layer.msg("提交失败", { icon: 5 });
              } else {
                layui.layer.msg("提交成功", { icon: 6 });
              }
              $("#batch").val("");

              layui.layer.close(addIndex);
            },
          });
          // return false
        } else {
          layui.layer.msg("请选择内容", { icon: 5 });
          return false;
        }
        // }
      });
    });
  }

  // 场景名称点击按钮
  var changjingPopIndex;
  $("#changjingPop").click(function (e) {
    e.preventDefault();
    console.log(treeData, "treeData");
    if (treeData.label == "scdw" && treeData.level == 5) {
      $(".superiorChangjing").val(treeData.title);
      console.log("dayin");
    } else {
      $(".superiorChangjing").text("未选择");
    }
    changjingPopIndex = layer.open({
      type: 1,
      title: ["新增场景名称", "font-size:18px;"],
      area: ["70%", "70%"],
      content: $("#newchangjingPop"),
      cancel: function (e) {
        console.log(e, "eee");
      },
    });
  });
  // 点击保存按钮新增场景
  $("#enterGroup").on("click", function (e) {
    e.preventDefault();
    let data = {};
    if (treeData.label == "scdw" && treeData.level == 5) {
      data.ejdwId = treeData.ejdwId;
      data.ejdwName = treeData.ejdwName;
      data.dw_3_id = treeData.dw_3_id;
      data.dw_3_name = treeData.dw_3_name;
      data.dw_4_id = treeData.dw_4_id;
      data.dw_4_name = treeData.dw_4_name;
      data.dw_5_id = treeData.dw_5_id;
      data.dw_5_name = treeData.dw_5_name;
      data.sceneId = treeData.id;
      data.sceneName = $(".changjingName").val();
      data.parentId = 0;
    }
    console.log(data, "data");
    /**
     * 接口为3.2序号
     */
    if (data.sceneId) {
      if (data.sceneName) {
        $.ajax({
          method: "post",
          url: "/youtian/scene-category",
          data: JSON.stringify(data),
          dataType: "json",
          contentType: "application/json",
          success: function (res) {
            if (res.code !== 0) return layui.layer.msg(res.msg, { icon: 5 });
            layui.layer.msg(res.msg, { icon: 6 });
            layui.layer.close(changjingPopIndex);
            $(".changjingName").val("");

            createTree("#tree1");
          },
        });
      } else {
        layui.layer.msg("必填项不能为空");
      }
    } else {
      layui.layer.msg("请先选择左侧场景树");
    }
  });

  /**
   * 场景下采集点位表格渲染
   */
  var addIndex = "";
  // 采集点位table
  var tableItem = ""; //获得当前行数据
  function tableList(data) {
    let tableData = data.rows ? data.rows : data;
    layui.use(["table", "layer", "laypage"], function () {
      var laypage = layui.laypage;
      var layer = layui.layer;
      var table = layui.table;
      var tableLL = table.render({
        elem: "#tableData",
        height: 442,
        limit: 10, // 默认显示几条数据
        cols: [
          [
            {
              field: "pointName",
              title: "采集数据点位",
              unresize: true,
              width: "20%",
              align: "center",
            },
            {
              field: "sceneName",
              title: "区域",
              width: "20%",
              align: "center",
            },
            {
              field: "dataState",
              title: "数据状态",
              width: "20%",
              align: "center",
            },
            {
              field: "dataState",
              title: "报警状态",
              sort: false,
              width: "20%",
              align: "center",
            },
            {
              field: "set",
              title: "操作",
              templet: "#tableDataBtn",
              width: "20%",
              align: "center",
            },
          ],
        ],
        data: tableData,
      });
      //单元格工具事件
      table.on("tool(test)", function (obj) {
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

        if (layEvent === "pointDel") {
          //删除
          layer.confirm("确定删除吗？", function (index) {
            console.log(obj, "delobj");
            let data = {
              pointId: obj.data.pointId,
              sceneId: obj.data.sceneId,
              id: obj.data.scenePointId,
            };
            $.ajax({
              url: `/youtian/scene-point/remove`,
              dataType: "json",
              headers: { "Content-Type": "application/json" },
              type: "post",
              data: JSON.stringify(data),
              success: function (res) {
                page.sceneId = detail.data.sceneId;
                $.ajax({
                  url: `/youtian/scene-category/scencePointlist`,
                  type: "get",
                  data: page,
                  success: function (res) {
                    tableList(res);
                  },
                });
              },
            });
            obj.del(); // 删除对应行（tr）的 DOM 结构，并更新缓存
            layer.close(index);
          });
        } else if (layEvent === "pointAdd") {
          porintIndex = layer.open({
            type: 1,
            title: ["修改监测点", "font-size:18px;"],
            area: ["70%", "70%"],
            content: $("#porintSet"),
            cancel: function () {
              console.log(obj);
            },
          });
          $(".porintValue").html(obj.data.pointName);

          // 当发送后端请求成功后，可再通过 reloadData 方法完成数据重载
          /*
          table.reloadData(id, {
            scrollPos: 'fixed'  // 保持滚动条位置不变 - v2.7.3 新增
          });
          */
          tableLL.reloadData();
        }
      });
      // 分页功能
      laypage.render({
        elem: "pages", //注意，这里的 test1 是 ID，不用加 # 号
        count: data.total, //数据总数，从服务端得到
        curr: page.pageNum,
        layout: ["prev", "page", "next", "skip"],
        limit: page.pageSize,
        jump: function (obj, first) {
          //obj包含了当前分页的所有参数，比如：
          console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
          console.log(obj.limit); //得到每页显示的条数
          page.pageSize = obj.limit;
          page.pageNum = obj.curr;
          console.log(page, "page");
          //首次不执行
          if (!first) {
            $.ajax({
              url: `/youtian/scene-category/scencePointlist`,
              type: "get",
              data: page,
              success: function (res) {
                tableList(res);
              },
            });
          }
        },
      });
    });
  }

  /**
   * 场景表格渲染
   */
  // 工具列点击事件
  var enterGroupindex = "";
  let editObj;
  let addObj;
  let detail;
  function tablePop(data) {
    layui.use(["layer", "util", "treeTable"], function () {
      let tableData = data.rows ? data.rows : data;
      var $ = layui.jquery;
      var layer = layui.layer;
      var treeTable = layui.treeTable;

      // 渲染表格
      var insTb = treeTable.render({
        elem: "#demo",
        // url: "json/menus.json",
        data: tableData,
        toolbar: "default",
        height: "500",
        width: "100%",
        tree: {
          iconIndex: 1,
          isPidData: true,
          idName: "sceneId",
          pidName: "parentId",
        },
        cols: [
          [
            { title: "ID", type: "numbers", width: "5%", align: "center" },
            {
              field: "sceneName",
              title: "场景名称",
              width: "25%",
            },
            {
              field: "zyqName",
              title: "对应区",
              align: "center",
              width: "12%",
            },
            {
              field: "dw_5_name",
              title: "对应站",
              width: "12%",
              align: "center",
            },
            {
              field: "deptName",
              title: "所属部门",
              width: "12%",
              align: "center",
            },
            {
              align: "center",
              toolbar: "#tbBar",
              title: "操作",
              width: "34%",
              align: "center",
            },
          ],
        ],
        style: "margin-top:0;",
      });

      treeTable.on("tool(demo)", function (obj) {
        var event = obj.event;

        console.log(obj.data, "sceneIds");
        if (event === "del") {
          let sceneId = obj.data.sceneId;
          $.ajax({
            method: "DELETE",
            url: `/youtian/scene-category/${sceneId}`,
            success: function (res) {
              console.log(res);
            },
          });
          layer.msg("删除成功");
          firstTable();
        } else if (event === "edit") {
          layui.use("tree", function () {
            var tree = layui.tree;
            setDataIndex = layer.open({
              type: 1,
              title: ["修改场景", "font-size:18px;"],
              area: ["60%", "80%"],
              content: $("#setArea"),
            });
            $(".setSpan").html(obj.data.sceneName);
          });
          editObj = obj;
          console.log(obj, "objedit");
        } else if (event === "detail") {
          detail = obj;
          console.log(detail, "detail");
          setDataIndex = layer.open({
            type: 1,
            title: ["采集数据点位详情", "font-size:18px;text-align:center"],
            area: ["100%", "100%"],
            content: $("#demotable"),
          });
          /**
           * 接口为序号3.3
           * 查询场景下点位列表
           */
          page.sceneId = detail.data.sceneId;
          $.ajax({
            url: `/youtian/scene-category/scencePointlist`,
            type: "get",
            data: page,
            success: function (res) {
              tableList(res);
            },
          });
        } else if (event === "add") {
          // 表格新增按钮
          addObj = obj;
          console.log(addObj, "addObj");
          enterGroupindex = layer.open({
            type: 1,
            title: ["新增场景", "font-size:18px;"],
            area: ["60%", "80%"],
            content: $("#enterGroup_class"),
          });
          $(".selectSpan").html(obj.data.sceneName);
        }
      });

      /**
       *
       * 保存提交录入信息
       *
       * @parms 区域组名称  必填
       * @parms 上级区域    选填
       *
       * */
      // 场景下新增场景按钮
      $("#enterGroup_sure").on("click", function () {
        let sceneName = $(".categoryName").val();
        let parentId = addObj.data.sceneId;
        let json = {
          sceneName: sceneName,
          parentId: parentId,
        };
        json.ejdwId = addObj.data.ejdwId;
        json.ejdwName = addObj.data.ejdwName;
        json.dw_3_id = addObj.data.dw_3_id;
        json.dw_3_name = addObj.data.dw_3_name;
        json.dw_4_id = addObj.data.dw_4_id;
        json.dw_4_name = addObj.data.dw_4_name;
        json.dw_5_id = addObj.data.dw_5_id;
        json.dw_5_name = addObj.data.dw_5_name;
        json.zyqId = addObj.data.zyqId;
        json.zyqName = addObj.data.zyqName;
        if (json.sceneName) {
          $.ajax({
            method: "post",
            url: "/youtian/scene-category",
            data: JSON.stringify(json),
            dataType: "json",
            headers: {
              "Content-Type": "application/json;charset=utf-8",
            },
            success: function (res) {
              if (res.code === 0) {
                layui.layer.msg(res.msg, { icon: 6 });
              } else if (res.code === 500) {
                return layui.layer.msg("录入工作区失败", {
                  icon: 5,
                });
              } else {
                return layui.layer.msg("录入失败", { icon: 5 });
              }
              firstTable();
              layer.close(enterGroupindex);
              $(".categoryName").val("");
            },
          });
        } else {
          layui.layer.msg("新增场景名称不能为空");
        }
      });

      // 设置区弹框
      // ----------------点击设置区域组 start
      var setDataIndex = "";
      // 点击设置提交保存
      $("#setAreaBtn").on("click", function () {
        let sceneName = $(".setDataName").val();
        console.log(editObj, "editObj");
        let sceneId = editObj.data.sceneId;
        if (sceneName == "") {
          layui.layer.msg("场景名称不能为空");
        } else {
          $.ajax({
            method: "put",
            url: "/youtian/scene-category",
            data: JSON.stringify({ sceneName, sceneId }),
            dataType: "json",
            headers: {
              "Content-Type": "application/json;charset=utf-8",
            },
            success: function (res) {
              if (res.code == "0") {
                layui.layer.msg(res.msg, { icon: 6 });
                firstTable();
              } else {
                layui.layer.msg(res.msg, { icon: 5 });
              }
              layui.layer.close(setDataIndex);
              $(".setDataName").val("");
            },
          });
        }
      });
      // ----------------点击设置区域组 end
    });
  }

  // 封装创建树方法
  function createTree(dom) {
    layui.use("tree", function () {
      var treeCkData = { id: 0 };
      var tree = layui.tree;
      // yang xiao xing 2022-12-2 修改
      var url = "/gzmx_scdw/gzmx_scdw/tree";
      // var url = "/gzmx_scdw/gzmx_scdw/temlateTreeDataNew";

      $.ajax({
        url: url,
        type: "get",
        success: function (res) {
          console.log(res, "tree");
          tree.render({
            elem: dom, //绑定元素
            data: res.data,
            click: function (obj) {
              console.log(obj, "obj");
              treeData = obj.data;
              // $.ajax({
              //   type: "get",
              //   url: "/youtian/scene-category/tree",
              //   success: function (res) {
              //     //   tableList(res)
              //   },
              // });
              // treeData = obj.data;
              if (obj.data.id !== treeCkData.id) {
                // 点击左侧工作树高亮显示
                $('div[data-id="' + obj.data.id + '"] span')
                  .eq(1)
                  .last()
                  .addClass("clickColor");
                $('div[data-id="' + treeCkData.id + '"] span')
                  .eq(1)
                  .last()
                  .removeClass("clickColor");
                treeCkData = obj.data;
              }
              $(".setDataName").val(obj.data.title);
              let page = {
                pageNum: 10,
                pageSize: 1000,
              }
              if (obj.data.level == 2){
                page.ejdwId = obj.data.ejdwId
              }else if(obj.data.level == 3) {
                page.dw_3_id = obj.data.dw_3_id
              }else if(obj.data.level == 4) {
                page.dw_4_id = obj.data.dw_4_id
              }else if(obj.data.level == 5) {
                page.dw_5_id = obj.data.dw_5_id
              }
              $.ajax({
                url: `/youtian/scene-category/list`,
                type: "get",
                data: page,
                success: function (res) {
                  tablePop(res);
                },
              });
              clickTreeId = obj.data.id;
              // obj.data.forEach((item) => {
              //   if (item.children) {
              //     item.children.forEach((it) => {
              //       if (it.children) {
              //         it.children;
              //       }
              //     });
              //   }
              // });
              // renderForm(obj.data.id,'','',false)
            },
          });
        },
      });
    });
  }
  // 点击新增出现弹框

  // 左侧树组件
  function leftTree() {
    createTree("#tree1");
  }
});
